<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>模拟VUE3中使用Proxy实现数据代理</h1>
</body>
<script>
    const data = {
        name: 'jack',
        dog: {
            name: '大黄',
            horse: {
                name: '白龙马',
                cat: {
                    name: 'homie'
                }
            }
        }
    }
    class Observable {
        constructor(data) {
            return new Proxy(this._observable(data), {
                get(target, key) {
                    console.log(key + '被读取了');
                    return Reflect.get(target, key)
                },
                set(target, key, value) {
                    console.log(key + '被修改了');
                    Reflect.set(target, key, value);
                }
            });
        }


        // 对data中的对象属性继续进行代理
        _observable(data) {
            for (let key in data) {
                if (typeof (data[key]) === 'object') {
                    // 递归
                    this._observable(data[key]);
                    data[key] = new Proxy(data[key], {
                        get(target, key) {
                            return Reflect.get(target, key)
                        },
                        set(target, key, value) {
                            Reflect.set(target, key, value);
                        }
                    });
                }
            }

            return data;
        }
    }
    const p = new Observable(data);
    console.log(p);
</script>

</html>